<template>
  <div class="wrapper">
    
    <header>
      <img src="../assets/大屏顶部图标.png" />
      <div class="back-button" @click="goBack">
        <i class="fa fa-arrow-left"></i>
        返回
      </div>
      <div class="left"></div>
      <div class="right">
        <i class="fa fa-clock-o"></i>
        {{ currentTime }}
        <button class="test-btn" @click="showTestDialog = true">
          <i class="fa fa-user-md"></i>
          
          茶饮推荐
        </button>
      </div>
    </header>

    <!-- 体质测试弹窗 -->
    <el-dialog
      v-model="showTestDialog"
      title="茶饮推荐"
      width="50%"
      :close-on-click-modal="false"
      class="test-dialog"
    >
      <el-form :model="testForm" label-width="120px">
        <el-form-item label="年龄">
          <el-input-number v-model="testForm.age" :min="1" :max="120" />
        </el-form-item>
        
        <el-form-item label="性别">
          <el-radio-group v-model="testForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="健康诉求">
          <el-checkbox-group v-model="testForm.healthNeeds">
            <el-checkbox label="减肥">减肥</el-checkbox>
            <el-checkbox label="抗衰">抗衰</el-checkbox>
            <el-checkbox label="改善睡眠">改善睡眠</el-checkbox>
            <el-checkbox label="提高免疫力">提高免疫力</el-checkbox>
            <el-checkbox label="改善消化">改善消化</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
   
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTestDialog = false">取消</el-button>
          <el-button type="primary" @click="submitTest">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="main">
      <aside style="display: flex; flex-direction: column; height: 90vh; background-color: #001432; padding: 20px;">
       <div style="padding: 10px; color: #fff; ">
            <h2 style="background: linear-gradient(45deg, #f8e8ba, #d09d54); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 8px;">以茶为媒，践行健康中国行动方针</h2>
            
            <h2 style="background: linear-gradient(45deg, #f8e8ba, #d09d54); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 8px;">传承国饮智慧，共绘全民健康蓝图</h2>
            <p style="font-size: 20px; line-height: 1.3;">
              您的体质为：<span style="color: #32ccee; background: linear-gradient(45deg, #f8e8ba, #d09d54); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">{{ physiques }}</span>
            </p>
            <p style="font-size: 16px; line-height: 1.6;">
              推荐饮用茶：<span style="background: linear-gradient(45deg, #f8e8ba, #d09d54); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">{{ recommendedTea }}     {{ aiRecommmend }}</span>
            </p>

          </div>

  
          <!-- <organ :pieData="pieArrData" style="height: 100%;width: 100%;"></organ> -->

          <TeaRecommendation :constitution="physiques"></TeaRecommendation>

        
        <!-- <div style="flex: 1; height: 320px; min-height: 0; border: 1px solid #333; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);">
          <TeaDistributionPie></TeaDistributionPie>
        </div> -->
        <div class="teaImprovement" style="border: 1px solid #333; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);">
          <TeaImprovementChart></TeaImprovementChart>
        </div>
      </aside>
      <section style="display: flex; flex-direction: column; padding: 20px;">
        <div class="map" style="flex: 2; margin-bottom: 20px; border: 1px solid #333; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);">
          <h1 class="mapType">全国{{ physiques }}人数分布示例（抽样人数：{{ sample }}）</h1>
          <ChinaMap :mapArrData="mapArrData" @province-click="handleProvinceClick"></ChinaMap>
        </div>
        <div class="statistics" style="flex: 1; border: 1px solid #333; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);">
          <TeaBrewing :constitution="physiques" style="height: 100%;"></TeaBrewing>
        </div>
        
      </section>
      <article style="display: flex; flex-direction: column; height: 90vh; padding: 20px;">
          <ConstitutionFeatures :constitution="physiques"></ConstitutionFeatures>
          <TeaTimeline></TeaTimeline>

        
        <!-- <HealthProgressChart :province="selectedProvince" style="height: 100%;border: 1px solid #333;width: 100%; margin-bottom: 10px; border-radius: 10px;"></HealthProgressChart> -->
  
      </article>
    </div>
  </div>
</template>

<script setup>

import TeaBrewing from "../components/TeaBrewing.vue";
import BarChart from "../components/BarChart.vue";
import GaugeChart from "../components/GaugeChart.vue";
import LineChart from "../components/LineChart.vue";
import ChinaMap from "../components/ChinaMap.vue";
import TeaDistributionPie from "../components/TeaDistributionPie.vue";
import ProvincePhysiquePie from "../components/ProvincePhysiquePie.vue";
import organ from "../components/Organ.vue";
import TeaCultureTimeline from "@/components/TeaCultureTimeline.vue";
import TeaImprovementChart from "../components/TeaImprovementChart.vue";
import HealthProgressChart from "../components/HealthProgressChart.vue";
import TeaTimeline from "../components/TeaTimeline.vue";
import ConstitutionFeatures from "../components/ConstitutionFeatures.vue";
import TeaRecommendation from "../components/TeaRecommendation.vue";
// import HealthTimeline from "@/components/HealthTimeline.vue";
import axios from "axios";
import { ref, onMounted, onUnmounted, toRef, watch, computed } from "vue";
import router from "@/router";
import { useRoute } from "vue-router";
import { ElMessage, ElLoading } from 'element-plus';

axios.defaults.baseURL = "http://localhost:8081";

//地图接收的体质
var physiques = ref("平和质");

const route = useRoute()
physiques.value = route.query.physique;

// 体质测试相关数据
const showTestDialog = ref(false);
const testForm = ref({
  age: 25,
  gender: 'male',
  healthNeeds: [],
  questions: {
    tired: false,
    coldSensitive: false,
    sweatEasily: false,
    dryMouth: false,
    internalHeat: false,
    anxious: false,
    bloating: false,
    allergic: false
  }
});
const aiRecommmend = ref('');

// 提交体质测试
const submitTest = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在分析体质...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  try {
    // 构建请求数据
    const requestData = {
      age: testForm.value.age,
      sex: testForm.value.gender === 'male' ? '男' : '女',
      demand: testForm.value.healthNeeds
    };

    // 发送请求到后端
    const response = await axios.post('/ai/call', requestData);

    if (response.data.code === 200) {
      // 更新体质类型
      // physiques.value = response.data.data.split('"')[1];
      aiRecommmend.value = "、"+response.data.data;
      // 显示推荐信息
      ElMessage({
        message: response.data.data,
        type: 'success'
      });
      
      // 关闭弹窗
      showTestDialog.value = false;
      
      // 重新获取数据
      init();
    } else {
      ElMessage({
        message: response.data.message || '测试失败，请重试',
        type: 'error'
      });
    }
  } catch (error) {
    console.error('体质测试请求失败:', error);
    ElMessage({
      message: '测试失败，请重试',
      type: 'error'
    });
  } finally {
    loading.close();
  }
};
//柱状图数据（省分组分项检测数据统计）
const provinceNameData = ref([]);
const spmValueData = ref([]);
const so2ValueData = ref([]);
const coValueData = ref([]);

//仪表盘数据（网格覆盖率数据统计）
const provinceCoverage = ref([]);
const cityCoverage = ref([]);

//饼图数据（指数级别分布统计）
const pieArrData = ref([]);

//折线图数据（12个月内趋势统计）
const linenameData = ref([]);
const linevalueData = ref([]);

//地图数据
const mapArrData = ref([]);

// 样本总数
const sample = ref(0);

//空气质量检测总数量与良好数量
const aqiCount = ref(0);
const aqiGoodCount = ref(0);
const selectedProvince = ref('河北省');

// 添加实时时间
const currentTime = ref('');

const maxProvince = ref({
  name: '',
  value: 0,
  teaRegion: '',
  teaTypes: []
})

// 体质推荐茶饮映射
const teaRecommendations = {
  '平和质': '绿茶',
  '气虚质': '红茶',
  '阳虚质': '红茶',
  '阴虚质': '白茶',
  '痰湿质': '乌龙茶',
  '湿热质': '绿茶',
  '血瘀质': '红茶',
  '气郁质': '花茶',
  '特禀质': '白茶'
}

// 计算推荐茶饮
const recommendedTea = computed(() => {
  return teaRecommendations[physiques.value] || '绿茶'
})

// 产茶区映射
const teaRegions = {
  '浙江省': '江南茶区',
  '福建省': '江南茶区',
  '安徽省': '江南茶区',
  '江西省': '江南茶区',
  '湖南省': '江南茶区',
  '湖北省': '江南茶区',
  '江苏省': '江南茶区',
  '广东省': '华南茶区',
  '广西壮族自治区': '华南茶区',
  '海南省': '华南茶区',
  '台湾省': '华南茶区',
  '四川省': '西南茶区',
  '贵州省': '西南茶区',
  '云南省': '西南茶区',
  '西藏自治区': '西南茶区',
  '河南省': '江北茶区',
  '陕西省': '江北茶区',
  '甘肃省': '江北茶区',
  '山东省': '江北茶区'
}

// 茶型映射
const teaTypes = {
  '浙江省': ['绿茶', '黄茶'],
  '福建省': ['乌龙茶', '红茶', '白茶'],
  '安徽省': ['绿茶', '黄茶'],
  '江西省': ['绿茶', '红茶'],
  '湖南省': ['黑茶', '黄茶'],
  '湖北省': ['绿茶', '红茶'],
  '江苏省': ['绿茶'],
  '广东省': ['乌龙茶', '红茶'],
  '广西壮族自治区': ['黑茶', '红茶'],
  '海南省': ['红茶'],
  '台湾省': ['乌龙茶', '红茶'],
  '四川省': ['绿茶', '黄茶'],
  '贵州省': ['绿茶', '红茶'],
  '云南省': ['普洱茶', '红茶'],
  '西藏自治区': ['藏茶'],
  '河南省': ['绿茶'],
  '陕西省': ['绿茶'],
  '甘肃省': ['绿茶'],
  '山东省': ['绿茶']
}

// 更新最大省份信息
const updateMaxProvince = () => {
  if (mapArrData.value && mapArrData.value.length > 0) {
    const max = mapArrData.value.reduce((prev, current) => {
      return prev.value > current.value ? prev : current
    })
    maxProvince.value = {
      name: max.name,
      value: max.value,
      teaRegion: teaRegions[max.name] || '非主要产茶区',
      teaTypes: teaTypes[max.name] || []
    }
  }
}

// 监听mapArrData变化
watch(() => mapArrData.value, () => {
  updateMaxProvince()
}, { deep: true })

// 更新时间函数
const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 设置定时器
let timer = null;
onMounted(() => {
  updateTime();
  timer = setInterval(updateTime, 1000);
});

// 清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

// 添加事件处理函数
const handleProvinceClick = (province) => {
  console.log('点击省份:', province)
  selectedProvince.value = province
}

const init = () => {
  //1、省分组分项检测数据统计
  axios
    .get("tcmsampledata/body", {
      params: {
        body: physiques.value
      }
    })
    .then((response) => {
      const result = response.data;
      mapArrData.value = result.data.tcmSampleDataVOList.map((item) => {
        return {
          name: item.local,
          value: item.count,
        };
      });
      // 计算样本总数
      sample.value = mapArrData.value.reduce((total, item) => total + item.value, 0);
      console.log(">>>",mapArrData.value);
    })
    .catch((error) => {
      console.log(error);
    });

  // //2、市网格覆盖率
  // axios
  //   .post("statistics/getCityCoverage")
  //   .then((response) => {
  //     cityCoverage.value.length = 0;
  //     cityCoverage.value.push({
  //       value: response.data
  //     });
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });

  // //3、省网格覆盖率
  // axios
  //   .post("statistics/getProvinceCoverage")
  //   .then((response) => {
  //     provinceCoverage.value.length = 0;
  //     provinceCoverage.value.push({
  //       value: response.data
  //     });
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });

  // //4、AQI指数级别分布统计
  // axios
  //   .post("statistics/listAqiDistributeTotalStatis")
  //   .then((response) => {
  //     pieArrData.value.length = 0;
  //     let arr = response.data;
  //     for(let i=0;i<arr.length;i++){
  //       pieArrData.value.push({
  //         name: arr[i].aqiExplain.substr(0,2),
  //         value: arr[i].total
  //       });
  //     }
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });

  // //5、12个月超标趋势统计数据
  // axios
  //   .post("statistics/listAqiTrendTotalStatis")
  //   .then((response) => {
  //     linenameData.value.length = 0;
  //     linevalueData.value.length = 0;

  //     let arr = response.data;
  //     for(let i=0;i<arr.length;i++){
  //       linenameData.value.unshift(arr[i].month.substr(5,2));
  //       linevalueData.value.unshift(arr[i].total);
  //     }
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });

  // //6、空气质量检测总数量
  // axios
  //   .post("statistics/getAqiCount")
  //   .then((response) => {
  //     aqiCount.value = response.data;
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });

  // //7、空气质量检测良好数量
  // axios
  //   .post("statistics/getAqiGoodCount")
  //   .then((response) => {
  //     aqiGoodCount.value = response.data;
  //   })
  //   .catch((error) => {
  //     console.log(error);
  //   });
};
init();

//使用轮询策略来保证可视化大屏数据的实时性
setInterval(() => {
  init();
}, 5000);

const healthData = [
  { year: "2016年", content: "《健康中国2030规划纲要》颁布，国民体质合格率87.2%，健康知识普及率62.5%8。" },
  { year: "2017年", content: "全民健身计划全面铺开，体质合格率升至87.6%，慢性病死亡率下降0.4个百分点4。" },
  { year: "2018年", content: "每千人口执业医师达2.49人，个人卫生支出占比降至27.7%，医联体建设加速4。" },
  { year: "2019年", content: "健康素养行动启动，中小学生每日锻炼1小时比例突破55%，健康产业规模5.5万亿6。" },
  { year: "2020年", content: "全面建成小康社会，国民体质合格率89.0%，健康知识普及率72%，食品抽检合格率97.6%4。" },
  { year: "2021年", content: "后疫情时代医疗资源扩容，执业医师数达2.82人/千人口，健康素养监测全国覆盖4。" },
  { year: "2022年", content: "重大慢性病过早死亡率降至15.2%，养老服务床位39.8张/千老人，健康产业规模7.4万亿4。" },
  { year: "2023年", content: "居民健康素养水平达29.7%（接近2030年目标），医保住院报销比例70.9%，人均预期寿命77.7岁47。" },
  { year: "2024年", content: "糖尿病防治行动启动，18岁及以上居民糖尿病知晓率目标60%，基层规范管理率70%1。" },
  { year: "2025年", content: "国民体质合格率91.5%（超目标0.3%），健康知识普及率81.2%，个人卫生支出占比" },
  { year: "2026年", content: "前列腺癌质控项目进入第二阶段，推动地市级医院规范化诊疗3。" },
  { year: "2027年", content: "慢性呼吸系统疾病死亡率目标降至8.5/10万，基层筛查能力提升1。" },
  { year: "2028年", content: "全国减盐行动深化，人均每日盐摄入量目标降至8克5。" },
  { year: "2029年", content: "癌症5年生存率冲刺45%，高血压/糖尿病规范管理率超75%4。" },
  { year: "2030年", content: "终期目标——人均预期寿命79岁，慢性病死亡率12%，健康产业规模16万亿10。" }
];

const scrollPosition = ref(0);
let scrollInterval = null;

const startHealthScroll = () => {
  const itemHeight = 60; // 每个项目的高度
  const totalHeight = healthData.length * itemHeight;
  const visibleHeight = 165; // 可见区域高度

  scrollInterval = setInterval(() => {
    scrollPosition.value -= 0.5; // 降低滚动速度
    
    // 当滚动到最后一个项目时，平滑回到顶部
    if (Math.abs(scrollPosition.value) >= totalHeight - visibleHeight) {
      scrollPosition.value = 0;
    }
  }, 20); // 增加更新频率使滚动更平滑
};

onMounted(() => {
  startHealthScroll();
});

onUnmounted(() => {
  if (scrollInterval) {
    clearInterval(scrollInterval);
  }
});

const goBack = () => {
  router.back();
};

</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100vh;
  background-color: #001432;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

header {
  width: 100%;
  font-weight: 300;
  color: #aaf9fc;
  position: relative;
  display: flex;
  justify-content: space-between;
  flex: 0 0 2vw;
}

header img {
  display: block;
  width: 100%;
}

header div {
  position: absolute;
  font-size: 1vw;
}

header .left {
  left: 20px;
  top: 0.9vw;
}

header .right {
  right: 20px;
  top: 0.9vw;
  display: flex;
  align-items: center;
  gap: 20px;
}

.test-btn {
  background: #32ccee;
  color: #fff;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.test-btn:hover {
  background: #28a8c4;
  transform: translateY(-2px);
}

.test-btn i {
  font-size: 16px;
}

.test-dialog {
  :deep(.el-dialog) {
    background: #001432;
    border: 1px solid #32ccee;
    border-radius: 10px;
  }

  :deep(.el-dialog__title) {
    color: #32ccee;
  }

  :deep(.el-dialog__body) {
    color: #fff;
  }

  :deep(.el-form-item__label) {
    color: #fff;
  }

  :deep(.el-radio__label) {
    color: #fff;
  }

  :deep(.el-checkbox__label) {
    color: #fff;
  }
}

.divider {
  color: #32ccee;
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #32ccee;
}

.main {
  flex: 1;
  width: 100%;
  display: flex;
  overflow: hidden;
}

.main aside,
.main article {
  flex: 1.2;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.main section {
  flex: 0 0 35%;
  display: flex;
  flex-direction: column;
  padding: 15px;
  height: 100%;
  overflow: hidden;
}

.main section .map {
  flex: 1.5;
  margin-bottom: 10px;
  border: 1px solid #333;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  position: relative;
  height: 45%;
  min-height: 250px;
  overflow: hidden;
}

.main section .statistics {
  flex: 1;
  border: 1px solid #333;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  height: 100%;
  min-height: 220px;
  margin-bottom: 15px;
}

.mapType {
  text-align: center;
  color: #f8e8ba;
  font-size: 18px;
  margin: 10px 0;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
  background: rgba(0, 20, 50, 0.5);
  padding: 5px 15px;
  border-radius: 4px;
  width: 80%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.main aside {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.main aside div {
  flex: 1;
  margin-bottom: 10px;
  border: 1px solid #333;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  min-height: 200px;
}

.main article {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.main article div {
  flex: 1;
  margin-bottom: 10px;
  border: 1px solid #333;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  min-height: 200px;
}

.main aside .grid-box ul {
  width: 100%;
  height: 100%;
  display: flex;
}

.main aside .grid-box ul li {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.main aside .grid-box ul li h4 {
  flex: 1;
  text-align: center;
  color: #fff;
  font-size: 14px;
}

.main aside .grid-box ul li div {
  flex: 4;
}

.main section .statistics h3 {
  text-align: center;
  font-size: 14px;
  color: #fff;
  margin-top: 20px;
}

.main section .statistics ul {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  color: #fff;
}

.main section .statistics ul li {
  display: flex;
  align-items: center;
}

.health-timeline {
  height: 100%;
  overflow: hidden;
  position: relative;
  background: rgba(0, 20, 50, 0.3);
  border-radius: 8px;
  padding: 10px;
}

.health-content {
  position: absolute;
  width: 100%;
  transition: transform 0.05s linear;
  will-change: transform;
}

.health-item {
  text-align: center;
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  color: #fff;
  padding: 5px;
  border-bottom: 1px solid rgba(50, 204, 238, 0.2);
  height: 60px;
  box-sizing: border-box;
}

.year {
  color: #32ccee;
  font-weight: bold;
  margin-right: 10px;
  min-width: 60px;
}

.content {
  font-size: 14px;
  line-height: 1.4;
  flex: 1;
}

.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  padding: 10px 20px;
  background: linear-gradient(135deg, rgba(0, 255, 255, 0.2) 0%, rgba(0, 255, 255, 0.3) 100%);
  color: #fff;
  border-radius: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  z-index: 100;
  font-size: 16px;
}
.back-button:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}
</style>